from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from .models import ToDo

# Create your views here.
def index(request):
    #从数据库读取所有todo
    todolist= ToDo.objects.all()
    if request.method == 'POST':
        #获取输入内容
        content= request.POST.get('content')
        #如果不为空,添加到数据库
        if content:
            ToDo.objects.create(content=content)
        else:
            messages.add_message(request, messages.INFO, '不能为空')

    if request.user.is_authenticated: #已登录
        return render(request, 'todolist/index.html', {'active': 'index', 'todolist': todolist})
    
    else:
        return redirect('/todo/login/')


def signup_view(request):
    notice=''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        password1 = request.POST.get('password1')
        if username and password and password1:  # 输入都不为空
            if password==password1: #两次密码相等
                User.objects.create_user(username=username,password=password)
                return redirect('/todo/login/')
            else:
                notice='密码不一致'
        else:
            notice='输入不能为空'
            
    return render(request, 'todolist/signup.html', {'notice': notice, 'active': 'signup'})

def login_view(request):
    notice=''
    if request.method == 'POST':
        #get input
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username and password: #输入都不为空, 验证存在
            user = authenticate(username=username,password=password)
            if user is not None:
                login(request, user)
                return redirect('/todo/')
            else:
                notice='用户名或密码错误'
        else:
            notice='不能为空'

    return render(request, 'todolist/login.html', {'notice': notice, 'active': 'login'})


def logout_view(request):
    logout(request)
    return redirect('/todo/login/')


def delete_todo(request):
    if request.method== 'POST':
        todo_id = request.POST.get('delete')
        g = ToDo.objects.filter(id=todo_id)
        g[0].delete()
    return redirect('/todo/')
